#!/usr/bin/env python3
"""
测试运行器

统一运行项目中的所有测试，包括：
- 单元测试
- 集成测试
- 功能测试

使用方法:
    python run_tests.py [--verbose] [--test-name TEST_NAME]
"""

import sys
import os
import argparse
import subprocess
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root / "src"))

def run_command(cmd, description):
    """运行命令并显示结果"""
    print(f"\n{'='*60}")
    print(f"🚀 {description}")
    print(f"{'='*60}")
    
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True, cwd=project_root)
        
        if result.stdout:
            print(result.stdout)
        
        if result.stderr:
            print("错误输出:")
            print(result.stderr)
        
        if result.returncode == 0:
            print(f"✅ {description} - 成功")
            return True
        else:
            print(f"❌ {description} - 失败 (退出码: {result.returncode})")
            return False
            
    except Exception as e:
        print(f"❌ {description} - 执行失败: {str(e)}")
        return False

def run_all_tests(verbose=False):
    """运行所有测试"""
    print("🧪 开始运行所有测试...")
    
    tests = [
        ("python -m pytest tests/ -v" if verbose else "python -m pytest tests/", "运行pytest测试套件"),
        ("python tests/test_baidu_auth.py", "运行百度认证功能测试"),
        ("python tests/test_logging_system.py", "运行日志系统测试"),
        ("python tests/test_task_2_1_logic.py", "运行任务2.1逻辑测试"),
    ]
    
    passed = 0
    total = len(tests)
    
    for cmd, description in tests:
        if run_command(cmd, description):
            passed += 1
    
    print(f"\n{'='*60}")
    print(f"🎯 测试总结: {passed}/{total} 通过")
    print(f"{'='*60}")
    
    if passed == total:
        print("🎉 所有测试通过！")
        return True
    else:
        print("⚠️ 部分测试失败，请检查上述错误信息")
        return False

def run_specific_test(test_name, verbose=False):
    """运行特定测试"""
    test_files = {
        "baidu_auth": "tests/test_baidu_auth.py",
        "logging": "tests/test_logging_system.py", 
        "task_2_1": "tests/test_task_2_1_logic.py",
        "pytest": "python -m pytest tests/" + (" -v" if verbose else "")
    }
    
    if test_name not in test_files:
        print(f"❌ 未知的测试名称: {test_name}")
        print(f"可用的测试: {', '.join(test_files.keys())}")
        return False
    
    cmd = f"python {test_files[test_name]}" if not test_name == "pytest" else test_files[test_name]
    return run_command(cmd, f"运行 {test_name} 测试")

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="Gamer520 测试运行器")
    parser.add_argument("--verbose", "-v", action="store_true", help="详细输出")
    parser.add_argument("--test-name", "-t", type=str, help="运行特定测试 (baidu_auth, logging, task_2_1, pytest)")
    
    args = parser.parse_args()
    
    print("🧪 Gamer520 测试运行器")
    print("=" * 60)
    
    if args.test_name:
        success = run_specific_test(args.test_name, args.verbose)
    else:
        success = run_all_tests(args.verbose)
    
    sys.exit(0 if success else 1)

if __name__ == "__main__":
    main()